<template>
  <div>
    <el-main>
      <el-row>
        <el-col :span="12" :xs="24">
          <div style="font-size: 24px; font-weight: bold; margin-bottom: 20px">
            添加走访
          </div>
          <div class="title"><span>1、</span><span>填写走访信息（必填）：</span></div>
          <el-form ref="form" :model="form" label-width="auto" :rules="rules">
            <el-row :gutter="20">
              <el-col :span="12" :xs="24">
                <el-form-item label="企业名称" prop="company">
                  <el-row style="">
                    <el-col :span="24">
                      <div style="display: flex">
                        <el-autocomplete ref="selectRef" clearable style="width: 100%" class="inline-input"
                          v-model="form.company" :fetch-suggestions="querySearch" placeholder="请输入公司名称"
                          :trigger-on-focus="false" @select="handleSelect">
                          <template slot-scope="{ item }">
                            <div class="name">{{ item.company_name }}</div>
                          </template>
                        </el-autocomplete>
                        <div style="display: flex; align-items: center">
                          <el-button :loading="buttonType" size="mini"
                            style="margin-left: 10px; font-size: 14px; height: 38px" type="primary" plain
                            @click="handleSearchTYC">搜索</el-button>
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                </el-form-item>

                <el-form-item label="走访人员" prop="Visitpeople">
                  <el-select style="width: 100%" filterable v-model="form.Visitpeople" multiple placeholder="" :disabled="pending" >
                    <el-option v-for="item in Visitpeoplelist" :key="item.user_id" :label="item.username"
                      :value="item.user_id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" :xs="24">
                <el-form-item label="所属镇街">
                  <el-select style="width: 100%" v-model="StreetId" placeholder="">
                    <el-option v-for="item in StreetList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="预计走访时间" prop="time">
                  <div style="display: flex;">
                    <el-date-picker type="datetime" placeholder="" align="right" v-model="form.time" :disabled="pending" 
                      value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%">
                    </el-date-picker>
                    <!-- <el-button @click="pending  = !pending" style="margin-left: 10px;font-size: 14px;" size="mini" type="primary">{{pending ? '已待定' : '待定'}}</el-button> -->
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="title"><span>2、</span><span>填写接待信息（非必填）：</span></div>

          <el-form ref="form2" :model="form_reception" label-width="80px">
            <el-form-item label="">
              <el-upload :class="{ hide: hideUpload }" :action="action" :limit="1" :file-list="fileList"
                :before-upload="beforeAlbumUpload" :on-success="onSuccess" list-type="picture-card">
                <div slot="default" style="width: 100%; height: 100%">
                  <img style="width: 100%; height: 100%; object-fit: cover" src="@/assets/web/card2.png" />
                </div>
                <div slot="file" slot-scope="{ file }" v-loading="file.status == 'uploading'">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="12" :xs="24">
                <el-form-item label="接待人员">
                  <el-input v-model="form_reception.username"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" :xs="24">
                <el-form-item label="联系电话" prop="company_name">
                  <el-input v-model="form_reception.mobile"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" :xs="24">
                <el-form-item label="邮箱" prop="company_name">
                  <el-input v-model="form_reception.email"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" :xs="24">
                <el-form-item label="地址" prop="company_name">
                  <el-input v-model="form_reception.address"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <div class="dialog-footer">
            <el-button type="primary" @click="preservation('form')">添加</el-button>
          </div>
        </el-col>
      </el-row>

      <el-dialog title="" :visible.sync="questionnaire" width="30%">
        <div class="questionnaireText">
          <div class="title">温馨提示</div>
          <div class="text">走访已添加成功，请按时前往走访。</div>
          <div class="text">是否同步创建企业调查问卷?</div>
        </div>
        <span slot="footer" class="questionnaireBox">
          <el-button class="btn1" type="primary" plain @click="questionnaireVisible(false)">暂不添加</el-button>
          <el-button class="btn2" type="primary" @click="questionnaireVisible(true)">马上添加</el-button>
        </span>
      </el-dialog>

      <el-dialog title="" :visible.sync="next" width="30%">
        <div class="questionnaireText">
          <div class="title">问卷创建成功</div>
          <div class="text">请将以下链接发送对方联系人填写</div>
          <div class="text">
            填写链接：
            <a target="_blank" :href="origin + '/#/questionNew?answer_id=' + answer_id">{{
              origin + "/#/questionNew?answer_id=" + answer_id
            }}</a>
          </div>
        </div>
        <span slot="footer" class="questionnaireBox">
          <el-button class="btn1" type="primary" plain @click="fz_url">复制链接</el-button>
          <el-button class="btn2" type="primary" @click="seeCompany">查看企业</el-button>
        </span>
      </el-dialog>
    </el-main>
  </div>
</template>

<script>

import {
  visitStreet,
  getBusinessCardInfo,
  seachCompany,
  createQuestion,
  companyInfo,
  createVisit,
  staff,
  getCompany,
} from "@/api/configApi";
import { VUE_APP_BASE_API } from "@/config.js";

export default {
  data() {
    var validateCompany = (rule, value, callback) => {
      if (!this.form.company_id && !this.form.company) {
        callback(new Error("请搜索并选择正确的公司"));
      } else {
        callback();
      }
    };
    return {
      pending: false,
      region_id: this.$store.state.user.region_id,
      origin: "",
      id: this.$store.state.user.id,
      options: [],
      choose: false,
      Visit: false,
      action: `${VUE_APP_BASE_API}/v1/config/upload`,

      company_id: "",

      SeachType: false,
      dialogImageUrl: "",
      dialogVisible: false,
      questionnaire: false,
      next: false,
      disabled: false,
      buttonType: false,
      Visitpeoplelist: [],
      form: {
        company_id: "",
        time: "",
        Visitpeople: [],
        company: "",
        enterprise: [],
      },
      form_reception: {
        username: "",
        mobile: "",
        email: "",
        address: "",
        business_card: "",
      },
      StreetId: "",
      answer_id: "",
      company: "",
      seachCompanyList: [],
      SelectCompanyName: "",
      StreetList: [],
      fileList: [],
      hideUpload: "",
      rules: {
        company: [{ required: true, validator: validateCompany, trigger: "blur" }],
        Visitpeople: [{ required: false, message: "请选择走访人员", trigger: "blur" }],
        time: [{ required: false, message: "请选择走访时间", trigger: "blur" }],
      },
    };
  },
  components: {},
  async mounted() {
    this.origin = window.location.origin;
    this.staff();
    await this.companyStreet();
    let company_name = this.$route.query.company_name
    let company_id = this.$route.query.company_id


    if (company_name && company_id) {
      this.form.company_id = company_id;
      this.company = company_name;
      this.form.company = company_name;
      this.StreetId = this.$route.query.street_id ? this.$route.query.street_id : this.StreetList[0].id
      this.companyInfo(company_id);

    } else if (company_name) {
      getCompany({ company: company_name }).then(res => {
        this.form.company_id = res.id
        this.companyInfo(res.id);
      })
      this.StreetId = this.$route.query.street_id ? this.$route.query.street_id : this.StreetList[0].id
      this.company = company_name;
      this.form.company = company_name;
    }

  },
  methods: {
    seeCompany() {
      this.$router.push({
        path: "/workEnterprisevisit",
        query: { company_id: this.company_id },
      });
    },
    handleRemove(file) {
      this.hideUpload = false;
      // 1.获取将要删除图片的临时路径
      const filePath = file.url;
      // 2.从pics数组中，找到图片对应的索引值
      const i = this.fileList.findIndex((x) => x.url === filePath);
      // 3.调用splice方法，移除图片信息
      this.fileList.splice(i, 1);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
    },
    handleSearchTYC() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (this.form.company == "") {
        this.$message({
          message: "请输入公司名称",
          type: "warning",
        });
        return;
      }
      this.buttonType = true;
      this.timer = setTimeout(() => {
        seachCompany({ keword: this.form.company, region_id: this.region_id }).then((res) => {
          this.buttonType = false;
          this.seachCompanyList = res.slice(0, 1000);
          var restaurants = this.seachCompanyList;
          this.$refs["selectRef"].$data.suggestions = restaurants;
          this.$refs.selectRef.focus();
        });
      }, 500);
    },
    querySearch(queryString, cb) {
      cb([]);

    },
    createFilter(queryString) {
      return (restaurant) => {
        return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      };
    },
    companyInfo(id) {
      companyInfo({
        company_id: id,
      }).then((res) => {
        this.form_reception.username = res.res.username;
        this.form_reception.mobile = res.res.mobile;
        this.form_reception.email = res.res.email;
        this.form_reception.address = res.res.address;
        this.fileList = [];
        if (res.res.business_card) {
          this.hideUpload = true;
          this.fileList.push({
            url: res.res.business_card,
          });
        }
      });
    },
    handleSelect(item) {
      if (item.id) {
        this.companyInfo(item.id);
      } else {
        getCompany({
          company: item.company_name
        }).then(res => {
          this.form.company_id = res.id
          this.companyInfo(res.id);
        })
      }

      if (this.SelectCompanyName != item) {
        this.company = item.company_name ? item.company_name : item;
        this.form = {
          company_id: "",
          time: "",
          Visitpeople: [],
          company: "",
          enterprise: [],
        };
        this.SelectCompanyName = item.company_name ? item.company_name : item;
        this.form.company_id = item.id ? item.id : item.company_name;
        this.form.company = item.company_name ? item.company_name : item;
        this.StreetId = item.street_id ? item.street_id : this.StreetList[0].id
      }
    },
    staff() {
      staff({
        region_id: this.region_id
      }).then((res) => {
        this.Visitpeoplelist = res.list;
      });
    },
    async companyStreet() {
      let data = await visitStreet({
        region_id: this.region_id
      });
      this.StreetList = data.list;
    },
    SelectCompany(item) {
      this.form = {
        company_id: "",
        time: "",
        Visitpeople: [],
        company: "",
        enterprise: [],
      };
      this.form.company_id = item;
      this.choose = false;
    },
    seachInputType() {
      this.SeachType = false;
    },
    //模糊查询
    seachCompany(query) {
      seachCompany({ keword: query, region_id: this.region_id }).then((res) => {
        this.seachCompanyList = res.slice(0, 1000);
      });
    },
    //关闭弹窗
    close() {
      this.$emit("close");
    },
    //保存
    preservation(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let demolabel;
          if (this.form.enterprise.length > 0) {
            demolabel = this.form.enterprise
              .map((item) => {
                return item.id;
              })
              .join(",");
          }
          createVisit({
            user_id: this.id,
            company_id: this.form.company_id,
            date: this.form.time,
            visit: this.form.Visitpeople.join(","),
            label: demolabel,
            street_id: this.StreetId,
            username: this.form_reception.username,
            address: this.form_reception.address,
            mobile: this.form_reception.mobile,
            email: this.form_reception.email,
            business_card: this.form_reception.business_card,
            type: 1
          })
            .then((res) => {
              this.$message.success("添加成功");

              this.company_id = res.company_id;
              this.questionnaire = true;
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        } else {
          this.$message.error("请填写必填信息");
          return false;
        }
      });
    },
    fz_url() {
      var cInput = document.createElement("textarea");
      cInput.value = `尊敬的企业负责人，您好。为了更好为您提供企业知识产权辅导服务，请您填写以下知识产权调查问卷。有任何疑问请随时与我联系。\r\n问卷填写地址：${this.origin + "/#/questionNew?answer_id=" + this.answer_id}`;
      document.body.appendChild(cInput);
      cInput.select(); // 选取文本框内容

      // 执行浏览器复制命令
      // 复制命令会将当前选中的内容复制到剪切板中（这里就是创建的input标签）
      // Input要在正常的编辑状态下原生复制方法才会生效

      document.execCommand("copy");

      this.$message({
        type: "success",
        message: "复制成功",
      });
      // 复制成功后再将构造的标签 移除
      document.body.removeChild(cInput);

      this.$router.go(-1);
    },
    questionnaireVisible(type) {
      if (type) {

        createQuestion({
          company_id: this.form.company_id,
        }).then((res) => {
          this.questionnaire = false;
          this.answer_id = res;
          this.next = true;
        });
      } else {
        this.$router.go(-1);
      }
    },
    beforeAlbumUpload(file) {
      //上传前验证
      const isIMG = file.type.slice(0, 5) === "image";
      if (!isIMG) {
        this.$message.error("请上传图片!");
      }
      return isIMG;
    },
    onSuccess(response, file, fileList) {
      this.hideUpload = true;
      this.fileList = fileList;

      getBusinessCardInfo({
        file_path: response.data.url,
      }).then((res) => {
        this.form_reception.email = res.email;
        this.form_reception.username = res.name;
        this.form_reception.address = res.address;
        this.form_reception.mobile = res.phone;
        this.form_reception.business_card = response.data.url;
        this.$message({
          message: "上传成功",
          type: "success",
        });
      });

    },
    handleChange(file, fileList) {
      this.fileList = fileList;

    },
  },
};
</script>

<style scoped lang="less">
::v-deep .el-upload-list__item {
  .el-loading-parent--relative {
    width: 100%;
    height: 100%;
  }
}

::v-deep .hide .el-upload--picture-card {
  display: none;
}

.el-main {
  margin: 20px 15px;
}

.title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
}

::v-deep .upload-demo {
  .el-upload {
    width: 100%;

    .upload {
      width: 500px;
      height: 300px;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}

::v-deep .el-upload--picture-card {
  width: 520px;
  height: 320px;
}

.seachCompanyList {
  position: absolute;
  top: 40px;
  background-color: #fff;
  z-index: 2;
  height: 200px;
  overflow: scroll;
  overflow-x: auto;
  border: 1px solid #f4f5f7;

  div {
    padding: 0 5px;
    cursor: pointer;
  }

  div:hover {
    background-color: #c1c1c1;
  }
}

.button_from_i {
  min-width: 125px;
  height: 38px;
  line-height: 0px;
  font-size: 14px;
  color: #3377ff;
  background-color: #ebf2ff;
  border: 1px solid #387dff;
}

.dialog-footer {
  margin-top: 30px;

  button {
    padding: 5px 30px;
    width: 139px;
    height: 38px;
    background: #387dff;
    border: 1px solid #e8ecef;
    border-radius: 19px;
    font-size: 14px;
  }
}

.questionnaireText {
  .title {
    font-weight: bold;
    font-size: 25px;
    color: black;
    margin-bottom: 30px;
  }

  .text {
    font-size: 16px;
    line-height: 20px;
  }
}

.questionnaireBox {
  button {
    padding: 5px 30px;
    width: 139px;
    height: 38px;
    border-radius: 19px;
    font-size: 14px;
  }

  .btn1 {
    background: #ecf5ff;
    color: #387dff;
    border: 1px solid #387dff;
  }

  .btn2 {
    background: #387dff;
    border: 1px solid #e8ecef;
  }
}

.b_bule {
  /*display: inline-block;*/
  background-color: #d3e2ff !important;
  margin: 3px 5px;
  border-radius: 5px;
  padding: 0px 10px;
  color: #387dff;
  font-size: 12px;
  height: 20px;
  line-height: 20px;
  border: none !important;
}

.b_choose {
  display: inline-block;
  background-color: #ffffff;
  margin: 3px 5px;
  border-radius: 5px;
  padding: 0px 10px;
  color: #387dff;
  font-size: 12px;
  height: 22px;
  line-height: 20px;
  border: 1px solid #387dff;
  cursor: pointer;
}

::v-deep .el-table__row td:nth-child(6) .el-button {
  color: #23b899;
  background-color: #ecfaf7;
  border: none;
  font-size: 14px;
}

::v-deep input {
  border-radius: 38px;
  height: 38px;
  line-height: 38px;
}

::v-deep .el-input__icon {
  line-height: 38px;
  font-size: 16px;
}

.Visitdate {
  margin-top: 62px;
}

::v-deep .el-table__row td:nth-child(7) .el-button {
  color: #23b899;
  background-color: #ecfaf7;
  border: none;
}

::v-deep .el-dialog {
  border-radius: 10px;
}

::v-deep .el-dialog__header {
  .el-dialog__title {
    font-size: 22px;
    font-weight: bolder;
  }

  .el-dialog__headerbtn {
    i {
      position: absolute;
      border: 3px solid #fff;
      top: -50px;
      left: 30px;
      color: #fff;
      border-radius: 30px;
      font-size: 24px;
      font-weight: bolder;
    }
  }
}

::v-deep .el-form-item {
  .el-form-item__label {
    font-size: 14px;
    font-weight: initial;
  }

  .el-form-item__content {
    .el-input__inner {
      border-radius: 5px;
    }
  }
}

@media (max-width: 768px) {
  .el-main {
    margin: 0;
    height: 100vh;
  }

  .Visitdate {
    margin-top: 0;
  }

  .el-form-item__content {
    .el-select {
      width: 100%;
    }
  }

  ::v-deep .el-popper {
    left: 22px !important;
  }
}

@media (max-width: 1280px) {}

@media (max-width: 1360px) {}
</style>
